package com.ecloud.common.web.jackson;

import java.util.List;

import com.ecloud.common.base.model.BaseVo;
import com.ecloud.common.base.translate.AutoTranslate;
import com.ecloud.common.web.translate.CustomSerializeFactory;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;

/**
 * 自定义序列化配置
 *
 * @author LiuGangQiang Create in 2021/08/19
 */
public class TranslateSerializerModifier extends BeanSerializerModifier {
    /**
     * 自定义序列化工厂
     *
     * @author LiuGangQiang Create in 2021/08/19
     */
    private CustomSerializeFactory factory;

    /**
     * 构造器
     *
     * @author LiuGangQiang Create in 2021/08/19
     * @param factory 自定义序列化工厂
     */
    public TranslateSerializerModifier(CustomSerializeFactory factory) {
        this.factory = factory;
    }

    @Override
    public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription bean, List<BeanPropertyWriter> beanProperties) {
        /* 只处理BaseVo的子类 */
        if (BaseVo.class.isAssignableFrom(bean.getBeanClass())) {
            for (BeanPropertyWriter writer : beanProperties) {
                /* 获取自动翻译注解 */
                AutoTranslate translate = writer.getAnnotation(AutoTranslate.class);
                /* 只处理有自动翻译注解的且设置需要翻译的值同时序列化的属性必须是字符串类型 */
                if (translate != null && translate.enable() && writer.getType().isTypeOrSubTypeOf(String.class)) {
                    /* 注册一个自定义的翻译序列化处理器 */
                    writer.assignSerializer(new TranslateFieldSerializer(this.factory, translate));
                }
            }
        }
        return beanProperties;
    }
}
